package net.lgpage.service;

import net.lgpage.http.ExceptionAsyncTask;
import net.lgpage.http.HttpConnectionUtil;
import net.lgpage.tool.GsonTool;
import net.lgpage.util.ReflectUtil;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.IBinder;


public class APKUpdateService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	public static String action = "com.lg.broadcast.apkupdate";
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		reloadObj();
		return super.onStartCommand(intent, flags, startId);
	}
	UpdateTask task;
	public void reloadObj(){
		if(task != null){
			task.cancel(true);
		}
		task = new UpdateTask(this);
		task.execute();
	}
	
	public VersionApk getVersionInfo(String packagename,String versiontype) throws Exception {
		String res = HttpConnectionUtil.requestUrl("http://api.fir.im/apps/latest/56e5063d00fc740a79000016?api_token=58aeedba1a88313b78807e7a8bed2044", "GET", null, "application/x-www-form-urlencoded");
		VersionApk va =GsonTool.getGson().fromJson(res, VersionApk.class);
		return va;
	}
	
	class UpdateTask extends ExceptionAsyncTask<VersionApk>{

		public UpdateTask(Context context) {
			super(context);
		}
		
		@Override
		public VersionApk doInBackgroundX(String... params) throws Exception {
			return getVersionInfo(getPackageName(),"1");
		}
		
		@Override
		public void onException(Exception e) {
			
		}
		@Override
		public void onPostExecuteX(VersionApk result) {
			if(result!=null){
				String version = result.getVersionShort();
				try {
					String versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
					System.out.println("app"+versionName+"-"+version);
					if(version!=null&&!version.equals(versionName)){
						Intent it = new Intent(action);
						it.putExtra("url", result.getInstallUrl());
						it.putExtra("must", "1");
						it.putExtra("content", result.getChangelog());
						sendBroadcast(it);
					}
				} catch (NameNotFoundException e) {
					
				}
			}else{
				
			}
		}
		
	}
}
